package com.webserver.core;

import com.webserver.http.EmptyRequestException;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.servlet.HttpServlet;

import java.io.File;
import java.net.Socket;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        System.out.println("开始处理.......");
        try {
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);

            String path = request.getRequestURI();

            HttpServlet servlet = ServletContext.getServlet(path);
            if (servlet!=null){
                System.out.println("=======================");
                servlet.service(request,response);
            } else {
                File file = new File("./webapps"+path);
                if (file.exists()&&file.isFile()){
                    System.out.println("资源存在");
                    response.setEntity(file);
                }else {
                    System.out.println("资源不存在");
                    response.setStatusCode(404);
                    response.setStatusReason("NotFound");
                    File NotFound = new File("./webapps/root/404.html");
                    response.setEntity(NotFound);
                }
            }

            response.flush();
            System.out.println("处理完毕！");
        } catch (EmptyRequestException e) {
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
